package sfeir.ergosum.myprofile;

import java.util.List;

import sfeir.ergosum.PreferencesActivity;
import sfeir.ergosum.R;
import sfeir.ergosum.menu.HiveMainMenuActivity;
import sfeir.ergosum.model.spreadsheet.SpreadsheetEntry;
import sfeir.ergosum.tools.SpreadsheetClient;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class SelectProfileActivity extends ListActivity {

    private static final int DIALOG_CREATE_OR_SELECT = 0;
    private static final int DIALOG_ENTER_TELDOM = 1;
    private SharedPreferences mPrefs;
    private ProgressDialog mProgress;
    private SpreadsheetClient mSpreadsheetClient = new SpreadsheetClient(new SpreadsheetClient.ResponseHandler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            if (mFinished)
                return;
            switch (msg.what) {
            case R.id.httpclient_ready:
                mProgress.setMessage(getString(R.string.authenticating));
                mProgress.setProgress(1000);

                String ids = mPrefs.getString("preference_loginpassKey", " \n ");
                String[] values;
                values = ids.split("\n");
                mSpreadsheetClient.setUserCredentials(values[0], values[1]);

                mSpreadsheetClient.handler.obtainMessage(R.id.request_login, R.id.client_auth_success, 0, "wise")
                        .sendToTarget();
                break;
            case R.id.client_get_spreadsheets:
                mSpreadsheetEntries = (List<SpreadsheetEntry>) msg.obj;
                mProgress.dismiss();
                for (SpreadsheetEntry key : mSpreadsheetEntries)
                    mAdapter.add(key);
                mSpreadsheetClient.terminate();
                mSpreadsheetClient = null;
                break;
            case R.id.client_auth_success:
                mProgress.dismiss();
                showDialog(DIALOG_CREATE_OR_SELECT);
                break;
            default:
                super.handleMessage(msg);
                break;
            }
        }
    });
    private ArrayAdapter<SpreadsheetEntry> mAdapter;
    private List<SpreadsheetEntry> mSpreadsheetEntries;
    private boolean mFinished;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mProgress = ProgressDialog.show(this, getString(R.string.profile_setting_up), "", false, true,
                new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (null != mSpreadsheetClient && mSpreadsheetClient.isAlive())
                            mSpreadsheetClient.terminate();
                        finish();
                    }
                });
        mAdapter = new ArrayAdapter<SpreadsheetEntry>(this, android.R.layout.simple_list_item_1);
        setListAdapter(mAdapter);
        setContentView(R.layout.profile_select_list);

        mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        String email = " ";
        String pass = " ";

        String ids = mPrefs.getString("preference_loginpassKey", " \n ");
        String[] values = ids.split("\n");
        email = values[0];

        if (values.length == 2)
            pass = values[1];

        if (" ".equals(email) || " ".equals(pass)) {
            showProfileFillInDialog();
            // Toast.makeText(this, "Fill in you credentials first", 3000);
            return;
        }
        if (null != mSpreadsheetClient && !mSpreadsheetClient.isAlive())
            mSpreadsheetClient.start();
    }

    private void showProfileFillInDialog() {
        new AlertDialog.Builder(this).setIcon(android.R.drawable.stat_notify_error).setMessage(
                R.string.profile_fill_in_authentification).setPositiveButton(R.string.preference_go_to_pref_screen,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PreferencesActivity.startPreferenceActionAuthentification(SelectProfileActivity.this);
                    }
                }).setNegativeButton(getString(R.string.profile_enter_teldom),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        showDialog(DIALOG_ENTER_TELDOM);
                    }
                }).setCancelable(true).setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (null != mSpreadsheetClient && mSpreadsheetClient.isAlive())
                    mSpreadsheetClient.terminate();
                finish();
            }
        }).show();
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        SpreadsheetEntry selectedEntry = mSpreadsheetEntries.get(position);
        String key = selectedEntry.getId();
        key = key.substring(key.lastIndexOf('/') + 1);
        mPrefs.edit().putString("profile_spreadsheet_key", key).commit();
        HiveMainMenuActivity.startProfileDetailsActivity(this, key);
        finish();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_CREATE_OR_SELECT:
            return new AlertDialog.Builder(this).setMessage(getString(R.string.profile_no_associated_profile))
                    .setPositiveButton(getString(R.string.profile_create_new), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(new Intent(SelectProfileActivity.this, NewProfileActivity.class));
                            finish();
                        }
                    }).setNegativeButton(getString(R.string.profile_select_profile),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mProgress.show();
                                    mProgress.setMessage(getString(R.string.listing_spreadsheets));
                                    mProgress.setProgress(6000);
                                    mSpreadsheetClient.handler.obtainMessage(R.id.request_spreadsheets).sendToTarget();
                                }

                            }).setNeutralButton(getString(R.string.profile_enter_teldom),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    showDialog(DIALOG_ENTER_TELDOM);
                                }
                            }).setCancelable(true).setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            if (null != mSpreadsheetClient && mSpreadsheetClient.isAlive())
                                mSpreadsheetClient.terminate();
                            finish();
                        }
                    }).create();
        case DIALOG_ENTER_TELDOM:
            final EditText etTelDom = new EditText(this);
            return new AlertDialog.Builder(this).setView(etTelDom).setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (null != mSpreadsheetClient && mSpreadsheetClient.isAlive())
                                mSpreadsheetClient.terminate();
                            String telDom = etTelDom.getText().toString();
                            if (!telDom.endsWith(".tel")) {
                                Toast.makeText(SelectProfileActivity.this, "Invalid .tel domain", 3000).show();
                                showProfileFillInDialog();
                                return;
                            }
                            mPrefs.edit().putString("profile_spreadsheet_key", telDom).commit();
                            HiveMainMenuActivity.startProfileDetailsActivity(SelectProfileActivity.this, telDom);
                            finish();
                        }
                    }).create();
        default:
            break;
        }
        return super.onCreateDialog(id);
    }

    @Override
    public void finish() {
        mFinished = true;
        super.finish();
    }
}
